<?php
/**
 * 注意：本内容仅限于博也公司内部传阅,禁止外泄以及用于其他的商业目的
 * @author    hebidu<346551990@qq.com>
 * @copyright 2018 www.itboye.com Boye Inc. All rights reserved.
 * @link      http://www.itboye.com/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 * Revision History Version
 ********1.0.0********************
 * file created @ 2018-01-09 14:26
 *********************************
 ********1.0.1********************
 *
 *********************************
 */

namespace app\index\command;


use app\src\baidu\LBSYunHelper;
use app\src\sunsun\common\logic\AllDeviceLocLogic;
use app\src\tool\helper\GeoHashHelper;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\exception\PDOException;

class Ip2LocationCommand extends Command
{
    /**
     * @var GeoHashHelper
     */
    private $helper;
    protected function configure()
    {
        $this->setName('ip2loc')
            ->addOption('interval', '', Option::VALUE_OPTIONAL, 'per process sleep {interval} seconds', 30)
            ->addOption('size', '', Option::VALUE_OPTIONAL, 'process sizes per time', 10)
            ->setDescription('all device ip convert to location(baidu longitude, latitude)');
    }

    protected function execute(Input $input, Output $output)
    {
        $size = $input->getOption('size');
        $interval = $input->getOption('interval');
        $queryNull = true;
        $logic = new AllDeviceLocLogic();
        $result = $logic->queryAllNewDevice($size, $queryNull);
        $queryNull = false;
        $result = $logic->queryAllNewDevice($size, $queryNull);
        $updateAll = [];
        $this->helper = new GeoHashHelper();
        if (is_array($result)) {
            $output->info(count($result));
            foreach ($result as $vo) {
                array_push($updateAll, $this->convertArray($vo['did'], $vo['ip'], $vo['delay'], $vo['last_login_time']));
            }

            if (count($updateAll)) {
                $logic->getModel()->startTrans();
                try {
                    $logic->saveAll($updateAll);
                    $logic->getModel()->commit();
                } catch (Exception $exception) {
                    try {
                        $logic->getModel()->rollback();
                    } catch (PDOException $e) {

                    }
                }
            }

        }
        // 处理ip
        $map =[
            'geohash' => ''
        ];
        $page = ['curpage'=>1, 'size'=>$size];
        $result = $logic->query($map, $page, "last_login_time desc");
        if ($result['status']) {
            $info = $result['info'];
            $list = $info['list'];
            if (is_array($list) && count($list) > 0) {
                $updateAll = [];
                foreach ($list as $vo1) {
                    array_push($updateAll, $this->convertArray($vo1['did'], $vo1['ip'], $vo1['delay'], $vo1['last_login_time']));
                }

                if (count($updateAll)) {
                    $logic->getModel()->startTrans();
                    try {
                        $logic->saveAll($updateAll);
                        $logic->getModel()->commit();
                    } catch (Exception $exception) {
                        try {
                            $logic->getModel()->rollback();
                        } catch (PDOException $e) {

                        }
                    }
                }
            }
        }

    }

    private function convertArray($did, $ip, $delay, $lastLoginTime)
    {
        $loc = $this->getLatLng($ip);
        $lng = '';
        $lat = '';
        $city = '';
        $cityCode = '';
        $province = '';
        if (array_key_exists('status', $loc) && $loc['status'] == 0) {
            $content = $loc['content'];
            // 经纬度
            if (array_key_exists('point', $content)) {
                $point = $content['point'];
                if (array_key_exists('x', $point)) {
                    $lng = $point['x'];
                }
                if (array_key_exists('y', $point)) {
                    $lat = $point['y'];
                }
            }

            // 城市编码
            if (array_key_exists('address_detail', $content)) {
                $address_detail = $content['address_detail'];
                if (array_key_exists('city', $address_detail)) {
                    $city = $address_detail['city'];
                }
                if (array_key_exists('city_code', $address_detail)) {
                    $cityCode = $address_detail['city_code'];
                }
                if (array_key_exists('province', $address_detail)) {
                    $province = $address_detail['province'];
                }

            }
        }
        $geohash = $this->helper->encode($lat, $lng);
        return [
            'did' => $did,
            'ip' => $ip,
            'province'=>$province,
            'lng' => $lng,
            'lat' => $lat,
            'geohash' => $geohash,
            'city' => $city,
            'city_code' => $cityCode,
            'delay' => $delay,
            'last_login_time' => $lastLoginTime
        ];
    }

    private function getLatLng($ip)
    {
        $loc = LBSYunHelper::locationIP($ip);
        return $loc;
    }
}